package com.itheima.advice;

import com.itheima.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class TransfarAdvice {
    @Autowired
    private LogService logService;

    @Pointcut("execution(* com.itheima.service.AccountService.transfer(..))")
    public void pt() {
    }

//    @Around("pt()")
//    public Object around(ProceedingJoinPoint pjp) {
//        //1.获取参数
//        Object[] args = pjp.getArgs();
//        String out = args[0].toString();
//        String in = args[1].toString();
//        double money = Double.parseDouble(args[2].toString());
//        Object proceed = null;
//        try {
//            //2.执行业务
//            proceed = pjp.proceed();
//            //3.1 返回通知的记录
//            String info = "转账成功!";
//            System.out.println(info);
//            logService.log(out, in, money);
//        } catch (Throwable e) {
//            //3.2 异常通知 - 失败原因
//            String info = "转账失败" + e.getMessage();
//            System.out.println(info);
//            logService.log(out, in, money, e.getMessage());
//            //环绕通知已经把异常处理掉了,所以不会回滚,手动抛出异常
//            throw new RuntimeException(info);
//        }
//        //4 后置通知 - 业务完成了
//        System.out.println("转账操作完成!");
//        return proceed;
//    }

    @AfterReturning(value = "pt()",returning = "obj")
    public void returning(JoinPoint point,Object obj){
        System.out.println("获得了返回值");
        Object[] args = point.getArgs();
        String out = args[0].toString();
        String in = args[1].toString();
        double money = Double.parseDouble(args[2].toString());

        logService.log(out,in,money);
    }

    @AfterThrowing(value = "pt()",throwing = "t")
    public void throwing(JoinPoint point,Throwable t){
        System.out.println("发生了异常");
        Object[] args = point.getArgs();
        String out = args[0].toString();
        String in = args[1].toString();
        double money = Double.parseDouble(args[2].toString());
        String info = t.getMessage();

        logService.log(out,in,money,info);
    }
}
